package application

import (
	"context"
	"github.com/edgexfoundry/edgex-go/internal/app/core/metadata/container"
	"github.com/edgexfoundry/edgex-go/internal/app/dtos"
	"github.com/edgexfoundry/edgex-go/internal/app/models"
	"github.com/edgexfoundry/edgex-go/internal/pkg/correlation"
	bootstrapContainer "github.com/edgexfoundry/go-mod-bootstrap/v2/bootstrap/container"
	"github.com/edgexfoundry/go-mod-bootstrap/v2/di"
	"github.com/edgexfoundry/go-mod-core-contracts/v2/errors"
)

func AddProductAttribute(pa models.ProductAttribute, ctx context.Context, dic *di.Container) (id string, edgeXerr errors.EdgeX) {
	dbClient := container.DBClientFrom(dic.Get)
	lc := bootstrapContainer.LoggingClientFrom(dic.Get)

	addedProductAttribute, err := dbClient.AddProductAttribute(pa)
	if err != nil {
		return "", errors.NewCommonEdgeXWrapper(err)
	}

	lc.Debugf(
		"Product Attribute created on DB successfully. Product Attribute ID: %s, Correlation-ID: %s ",
		addedProductAttribute.Id,
		correlation.FromContext(ctx),
	)

	return addedProductAttribute.Id, nil
}

func AttributesByProductId(offset int, limit int, productId string, dic *di.Container) (productAttributes []dtos.ProductAttribute, totalCount uint32, err errors.EdgeX) {
	dbClient := container.DBClientFrom(dic.Get)
	productAttributeMoedls, err := dbClient.AttributesByProductId(offset, limit, productId)
	if err == nil {
		totalCount, err = dbClient.AttributeCountByProductId(productId)
	}
	if err != nil {
		return productAttributes, totalCount, errors.NewCommonEdgeXWrapper(err)
	}
	productAttributes = make([]dtos.ProductAttribute, len(productAttributeMoedls))
	for i, pa := range productAttributeMoedls {
		productAttributes[i] = dtos.FromProductAttributeModelToDto(pa)
	}
	return productAttributes, totalCount, nil
}

func ProductAttributeDelete(productAttributeIds []string, dic *di.Container) errors.EdgeX {
	dbClient := container.DBClientFrom(dic.Get)
	err := dbClient.ProductAttributeDelete(productAttributeIds)
	if err != nil {
		return errors.NewCommonEdgeXWrapper(err)
	}
	return nil
}

func UpdateProductAttribute(productAttribute models.ProductAttribute, dic *di.Container) errors.EdgeX {
	dbClient := container.DBClientFrom(dic.Get)
	lc := bootstrapContainer.LoggingClientFrom(dic.Get)

	err := dbClient.UpdateProductAttribute(productAttribute)
	if err != nil {
		return errors.NewCommonEdgeXWrapper(err)
	}
	lc.Debugf("产品属性更新完成")
	return nil
}
